package com.tron.dobest.dynamicdatasource;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * 描述： 切面方法拦截并切换数据源
 *
 * @author TRON
 * @since 2020-04-20
 */
//@Component        //根据配置文件中的条件注入此bean
@Aspect
@Slf4j
public class SwitchOverDataSource {
    @Pointcut("execution(* com.tron.dobest.dynamicdatasource.TronDataSourceTestController.*(..))")
    public void tronPointcutOne() {}


    @Around("tronPointcutOne()")
    public Object around(ProceedingJoinPoint joinPoint) {
        log.info("========切换数据源=========");
        DynamicDataSourceContextHolder.setDataSource("second");
        try {
            return joinPoint.proceed();
        } catch (Throwable throwable) {
            //封装异常处理信息
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("code", 500);
            hashMap.put("message", throwable.getMessage());
            return hashMap;
        } finally {
            log.info("========清空数据源========");
            DynamicDataSourceContextHolder.clearDataSource();
        }
    }





}
